package sit.engreal.leetcode.problems400;

/**
 * <a href="https://leetcode.cn/problems/guess-number-higher-or-lower/">374. 猜数字大小</a>
 */
public class LeetCode374 {
    public static class GuessGame {
        private int n;
        private int count = 0;

        public void reset(int n) {
            this.n = n;
            this.count = 0;
        }

        /**
         * Forward declaration of guess API.
         *
         * @param num your guess
         * @return -1 if num is lower than the guess number
         * 1 if num is higher than the guess number
         * otherwise return 0
         * int guess(int num);
         */
        int guess(int num) {
            count++;
            return Integer.compare(num, n);
        }

        public int getCount() {
            return this.count;
        }
    }

    public static class Solution extends GuessGame {
        public int guessNumber(int n) {
            int left = 1, right = n;
            while (left < right) {
                int mid = left + (right - left) / 2; // 防止计算时溢出
                if (guess(mid) <= 0) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            return left;
        }
    }
}
